//
//  FoodManagementVC.m
//  dyseller
//
//  Created by 红喇叭 on 2017/11/18.
//  Copyright © 2017年 红喇叭. All rights reserved.
//

#import "FoodManagementVC.h"
#import "LeftScrollView.h"
#import "RightViewCell.h"
#import "FoodSortVC.h"
#import "FoodClassVC.h"
#import "AddFoodVC.h"
#import "EditFoodInfoVC.h"
#import "HLBShopeDefaultView.h"
#import "CategoryListModel.h"


#define TopViewHeight 48
@interface FoodManagementVC ()<LeftScrollViewdelegate,UITableViewDelegate,UITableViewDataSource>{
    LeftScrollView *_leftView;
    NSInteger allrow;
    NSArray *_categoryArray;
    NSArray *_goodsArray;
    HLBShopeDefaultView *_defaultView;
    BOOL isBack;//判断是否是返回引起的刷新
    BOOL isCategorCrash;//是否是列表加载异常
}


@property (nonatomic,strong)UITableView *rightTableView;
@end

@implementation FoodManagementVC

- (void)viewDidLoad {
    [super viewDidLoad];
    allrow = 0;
    [self setNavTitle:@"商品管理" titleColor:[UIColor blackColor] font:font17];
    [self initTopView];
    [self initleftView];
    [self.view addSubview:self.rightTableView];
    _rightTableView.tableFooterView = [UIView new];
    _categoryArray = [[NSArray alloc] init];
    _goodsArray = [[NSArray alloc] init];
  
   
    
    
}

- (void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
    [self  getCategoryList];
}




- (void)initTopView{
    UIView *topView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, self.view.width, TopViewHeight)];
    topView.backgroundColor = kWhiteColor;
    [self.view addSubview:topView];

    NSArray *imgAr = @[@"edit_nav_icon1_default_nor",@"edit_nav_icon2_default_nor",@"edit_nav_icon3_default_nor"];
    NSArray *titleArr = @[@"分类",@"排序",@"新增"];
    for(int i=0;i<imgAr.count;i++){
        UIButton *addFoodClass = [[UIButton alloc] initWithFrame:CGRectMake(GETWITH(74)+GETWITH(250)*i, GETHEIGHT(30), GETWITH(200), GETHEIGHT(42))];
        addFoodClass.titleLabel.font = font15;
        addFoodClass.tag = i;
        [addFoodClass setTitle:titleArr[i] forState:0];
        [addFoodClass setImage:[UIImage imageNamed:imgAr[i]] forState:UIControlStateNormal];
        [addFoodClass setTitleColor:UIColorFromRGB(0x323333) forState:0];
        [addFoodClass addTarget:self action:@selector(addFoodClassAction:)
               forControlEvents:UIControlEventTouchUpInside];
        addFoodClass.imageEdgeInsets = UIEdgeInsetsMake(0,-(addFoodClass.frame.size.width +addFoodClass.imageView.frame.size.width)/2.0f, 0, 0);
        addFoodClass.titleEdgeInsets = UIEdgeInsetsMake(0, 0,0,(addFoodClass.frame.size.width -addFoodClass.imageView.frame.size.width)/2.0f);
         [topView addSubview:addFoodClass];

    }
    
}


#pragma  mark ========网络请求========
//获取分类列表
- (void)getCategoryList{
    
    __weak typeof (self)weakself = self;
    [[PPHttpRequsetData shareInstance] requestStyle:Request_POST URL:@"/ShopApi/GoodsCate/categoryList" isactive:NO parameter:@{} successBlock:^(PPHttpRequest *request, NSArray* responseObj) {
        if(responseObj.count>0){
            [weakself setDefaultCategoryView:NO];
            NSMutableArray *arr = @[].mutableCopy;
            NSMutableArray *labelArr = @[].mutableCopy;
            [responseObj enumerateObjectsUsingBlock:^(id  _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
                CategoryListModel *model = [CategoryListModel yy_modelWithJSON:obj];
                [arr addObject:model];
                [labelArr addObject:model.category_name];
            }];
            _categoryArray = arr;
            _leftView.allLabelData = labelArr;
            [weakself getCategorycontent:_categoryArray[allrow]];

        }else{
            [weakself setDefaultCategoryView:YES];
        }
        [weakself removeExceptionView];
    } failBlock:^(PPHttpRequest *request, NSString *errMsg) {
        isCategorCrash = YES;
        [weakself addExceptionAlView];
        weakself.exView.frame = CGRectMake(0, TopViewHeight, SCREEN_W, SCREEN_H-TopViewHeight);
        [AlertUtils showToastWithMessage:errMsg inView:self.view hideAfterDelay:2.0 beIndeter:NO];
        
    }];
}

- (void)getCategorycontent:(CategoryListModel *)model{
    
    __weak typeof (self)weakself = self;
    [[PPHttpRequsetData shareInstance] requestStyle:Request_POST URL:@"/ShopApi/Goods/cateGoodsList" isactive:NO parameter:@{@"category_id":model.categoryID} successBlock:^(PPHttpRequest *request, NSArray* responseObj) {
        
        NSMutableArray *arr = @[].mutableCopy;
        [responseObj enumerateObjectsUsingBlock:^(id  _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
            CategoryContentModel *model = [CategoryContentModel yy_modelWithJSON:obj];
            [arr addObject:model];
        }];
        _goodsArray = arr;
        [_rightTableView reloadData];
        if(_goodsArray.count>0){
            [self setDefaultView:NO];
        }else{
            [self setDefaultView:YES];
        }
        
        if(_goodsArray.count>0 && isBack){
            [_rightTableView scrollToRowAtIndexPath:[NSIndexPath indexPathForRow:0 inSection:0] atScrollPosition:UITableViewScrollPositionTop animated:YES];
            isBack = NO;
        }

         [weakself removeExceptionView];
    } failBlock:^(PPHttpRequest *request, NSString *errMsg) {
        isCategorCrash = NO;
        [weakself addExceptionAlView];
        weakself.exView.frame = _rightTableView.frame;
        [AlertUtils showToastWithMessage:errMsg inView:self.view hideAfterDelay:2.0 beIndeter:NO];
        
    }];
}

- (void)buttonAction{
    __weak typeof(self)weakself = self;
    if(isCategorCrash){
        [weakself getCategoryList];
    }else{
        [weakself getCategorycontent:_categoryArray[allrow]];
    }
   
}

#pragma  mark ========缺省背景图========

//分类下没有商品
- (void)setDefaultView:(BOOL)isMove{
    if(_defaultView == nil && isMove){
        _defaultView = [[HLBShopeDefaultView alloc] initWithFrame:_rightTableView.bounds hintName:@"edit_note4_default" hintTitle:@"该分类下暂时没有商品"];
        __weak typeof (self)weakself = self;
        [_defaultView.actionBtn setTitle:@"+添加商品" forState:0];
        [_defaultView.actionBtn handleControlEvent:UIControlEventTouchUpInside withBlock:^(id sender) {
            AddFoodVC *vc = [AddFoodVC new];
            vc.categoryArray = _categoryArray;
            CategoryListModel *model = _categoryArray[allrow];
            vc.category_id = model.categoryID;
            [weakself.navigationController pushViewController:vc animated:YES];

        }];
        [_rightTableView addSubview:_defaultView];
    }else if(_defaultView && !isMove){
        [_defaultView removeFromSuperview];
        _defaultView = nil;
    }
}
//店铺下没有分类
- (void)setDefaultCategoryView:(BOOL)isMove{
    if(_defaultView == nil && isMove){
        _defaultView = [[HLBShopeDefaultView alloc] initWithFrame:CGRectMake(0, TopViewHeight, SCREEN_W, SCREEN_H-TopViewHeight) hintName:@"edit_note5_default" hintTitle:@"您还没有添加任何分类"];
        __weak typeof (self)weakself = self;
        [_defaultView.actionBtn setTitle:@"+添加分类" forState:0];
        [_defaultView.actionBtn handleControlEvent:UIControlEventTouchUpInside withBlock:^(id sender) {
            FoodClassVC *classVC = [FoodClassVC new];
            [weakself.navigationController pushViewController:classVC animated:YES];
            
        }];
        [self.view addSubview:_defaultView];
    }else if(_defaultView && !isMove){
        [_defaultView removeFromSuperview];
        _defaultView = nil;
    }
}

#pragma  mark ========分类，排序，新增，删除，点击方法========
- (void)addFoodClassAction:(UIButton *)btn{
    switch (btn.tag) {
        case 0:{
            FoodClassVC *classVC = [FoodClassVC new];
            [self.navigationController pushViewController:classVC animated:YES];
        }
            break;
        case 1:{
            if(_goodsArray.count<1){
               [AlertUtils showToastWithMessage:@"当前分类没有商品" inView:self.view hideAfterDelay:1.0 beIndeter:NO];
                return;
            }
            FoodSortVC *vc = [FoodSortVC new];
            vc.foodTitle = _leftView.allLabelData[allrow];
            vc.model = _categoryArray[allrow];
             [self.navigationController pushViewController:vc animated:YES];
        }
            break;
        case 2:{
            AddFoodVC *vc = [AddFoodVC new];
            vc.categoryArray = _categoryArray;
             [self.navigationController pushViewController:vc animated:YES];
        }
            break;
        default:
            break;
    }
}


- (void)initleftView{
    _leftView = [[LeftScrollView alloc] initWithFrame:CGRectMake(0, 50, GETWITH(170), SCREEN_H-48-NavigationHeight-TableSafe)];
    _leftView.delegate = self;
    
    [self.view addSubview:_leftView];
}

- (UITableView *)rightTableView{
    if(_rightTableView==nil){
        _rightTableView = [[UITableView alloc] initWithFrame:CGRectMake(_leftView.right, _leftView.top, self.view.width-_leftView.right, _leftView.height) style:UITableViewStyleGrouped];
        _rightTableView.dataSource = self;
        _rightTableView.delegate = self;
        _rightTableView.estimatedRowHeight = 95;
        _rightTableView.backgroundColor = kWhiteColor;
        [_rightTableView registerClass:[RightViewCell class] forCellReuseIdentifier:@"RightViewCell"];
        
    }
    return _rightTableView;
}

#pragma  mark ========UITableView 的代理方法========
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    return _goodsArray.count;
}

- (UITableViewCell*)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    RightViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"RightViewCell" forIndexPath:indexPath];
//    RightViewCell *cell = nil;
//    if(cell == nil){
//        cell = [[RightViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"RightViewCell"];
//    }
    cell.selectionStyle = UITableViewCellSelectionStyleNone;
    cell.categoryContentModel = (CategoryContentModel*)_goodsArray[indexPath.row];
    
    cell.shelvesBtn.tag = indexPath.row;
    [cell.shelvesBtn addTarget:self action:@selector(giveOrTakeAction:) forControlEvents:UIControlEventTouchUpInside];
    __weak typeof (self)weakself = self;
    [cell.editorBtn handleControlEvent:UIControlEventTouchUpInside withBlock:^(id sender) {
        CategoryContentModel *model =  _goodsArray[indexPath.row];
        EditFoodInfoVC *vc = [EditFoodInfoVC new];
        vc.goodsID = model.goodID;
        vc.categoryArray = _categoryArray;
        [weakself.navigationController pushViewController:vc animated:YES];
    }];
    return cell;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    CategoryContentModel *model = _goodsArray[indexPath.row];
    CGSize titleSize = [model.goods_name boundingRectWithSize:CGSizeMake(GETWITH(380), MAXFLOAT) options:NSStringDrawingUsesLineFragmentOrigin attributes:@{NSFontAttributeName:font16} context:nil].size;

    return 118 + titleSize.height;
}

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section{
    return 32;
}

- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section{
    UIView *headerV = [[UIView alloc] initWithFrame:CGRectMake(0, 0, SCREEN_W, 32)];
    headerV.backgroundColor = ControllerColor;
    UILabel *classTitle = [[UILabel alloc] init];
    classTitle.text = _leftView.allLabelData[allrow];
    classTitle.textColor = UIColorFromRGB(0x323333);
    classTitle.font = font12;
    [headerV addSubview:classTitle];
    classTitle.sd_layout.leftSpaceToView(headerV, GETWITH(20)).centerYEqualToView(headerV).heightIs(24).widthIs(200);
    return headerV;
}

- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section{
    return 0.1;
}

- (UIView*)tableView:(UITableView *)tableView viewForFooterInSection:(NSInteger)section{
    UIView *headerV = [[UIView alloc] initWithFrame:CGRectMake(0, 0, SCREEN_W, 0.1)];
    headerV.backgroundColor = tableView.backgroundColor;
    return headerV;
}
#pragma  mark ========LeftScrollViewdelegate========
- (void)leftScrollSelectIndex:(NSIndexPath *)index{
    allrow = index.row;
    isBack = YES;
    __weak typeof (self)weakself = self;
    [weakself getCategorycontent:_categoryArray[allrow]];
}

#pragma  mark ========上下架的网络请求========
- (void)giveOrTakeAction:(UIButton *)btn{
    
    CategoryContentModel *model = _goodsArray[btn.tag];
    
    __weak typeof (self)weakself = self;
    [[PPHttpRequsetData shareInstance] requestStyle:Request_POST URL:@"/ShopApi/Goods/goodsSetSale" isactive:NO
        parameter:@{@"is_on_sale":[model.is_on_sale isEqualToString:@"0"]?@"1":@"0",
                    @"goods_ids":model.goodID
                    }
      successBlock:^(PPHttpRequest *request, NSArray* responseObj) {
        
          NSString *messgae = [model.is_on_sale isEqualToString:@"0"]?@"上架成功！！":@"下架成功！！";
        [AlertUtils showToastWithMessage:messgae inView:self.view hideAfterDelay:1.0 beIndeter:NO];
        model.is_on_sale = [model.is_on_sale isEqualToString:@"0"]?@"1":@"0";
        [weakself.rightTableView reloadRowsAtIndexPaths:@[[NSIndexPath indexPathForRow:btn.tag inSection:0]] withRowAnimation:UITableViewRowAnimationNone];
          
    } failBlock:^(PPHttpRequest *request, NSString *errMsg) {
        
        [AlertUtils showToastWithMessage:errMsg inView:self.view hideAfterDelay:2.0 beIndeter:NO];
        
    }];

}

@end
